package handlers

import (
	"context"
	"flag"
	"fmt"
	"mediumkube/pkg/common"
	"mediumkube/pkg/extensions"
	"os"

	"github.com/olekukonko/tablewriter"
)

const (
	OP_EXEC  = "exec"
	OP_LIST  = "list"
	OP_CLEAN = "clean"
)

type ExtensionHandler struct {
	flagset *flag.FlagSet
}

func (h ExtensionHandler) Help() {
	fmt.Println("exec: Execute all extensions")
	fmt.Println("list: List declared extensions")
	fmt.Println("clean: Clean up extensions")
}

func (h ExtensionHandler) Desc() string {
	return "Execute extensions"
}

func dispExtensions(extensions []common.ExtensionVO) {
	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{
		"Name", "Image", "IP", "Port", "Message",
	})
	for _, v := range extensions {
		table.Append(
			[]string{v.Name, v.Image, v.IP, v.Port, v.Message},
		)
	}
	table.Render()
}

func (h ExtensionHandler) Handle(args []string) {
	if len(args) < 2 {
		h.Help()
		return
	}
	if Help(h, args) {
		return
	}
	operation := args[1]
	switch operation {
	case OP_EXEC:
		extensions.RunExtensions(context.TODO())
	case OP_LIST:
		exts := extensions.ListExtensions(context.TODO())
		dispExtensions(exts)
	case OP_CLEAN:
		extensions.CleanUpExtensions()
	default:
		h.Help()
	}
}

func init() {
	name := "ext"

	CMD[name] = ExtensionHandler{
		flagset: flag.NewFlagSet(name, flag.ExitOnError),
	}
}
